/*
 * SunSpotGloveHostTest1App.java
 *
 * Created on 2009-11-20 18:42:05;
 */
package org.sunspotworld;

import com.sun.spot.io.j2me.radiogram.*;

import java.io.*;
import javax.microedition.io.*;

/**
 * Sample Sun SPOT host application
 */
public class SunSpotGloveHostTest1App {

    private static final int HOST_PORT = 100;
    private static final int REFRESH_FREQUENCY = 50;  //Hz
    private static boolean CONNECT_ONCE = false;
    private RadiogramConnection conn;
    private Datagram dg;

    public void run() {

        if (CONNECT_ONCE) {
            try {
                conn = (RadiogramConnection) Connector.open("radiogram://:" + HOST_PORT);
                dg = conn.newDatagram(conn.getMaximumLength());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        long time = System.currentTimeMillis();

        while (true) {

            long oldtime = time;
            time = System.currentTimeMillis();
            System.out.println("\nOd ostatniego pomiaru minelo: " + (time - oldtime) + "ms");

            String rawData = readMessage();
            System.out.println("Blokowalem na polaczeniu " + (System.currentTimeMillis() - time) + "ms");
            System.out.println("Numer odebranej ramki: " + rawData);
            
            try {
                long czas = Math.max(0, 1000 / REFRESH_FREQUENCY - (System.currentTimeMillis() - time));
                System.out.println("Bedziemy spali " + czas + "ms");
                Thread.sleep(czas);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    private String readMessage() {

        String result = null;

        try {
            if (!CONNECT_ONCE) {
                conn = (RadiogramConnection) Connector.open("radiogram://:" + HOST_PORT);
                dg = conn.newDatagram(conn.getMaximumLength());
            }

            try {
                conn.receive(dg);
                result = dg.readUTF();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            if (!CONNECT_ONCE) {
                conn.close();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {

        SunSpotGloveHostTest1App app = new SunSpotGloveHostTest1App();
        app.run();
    }
}
